package com.study.springbootsecurity.util;

/**
 * @Description: TODO 统一结果放回
 * @author: Huangjianyun
 * @date: 2025-06-03 19:10
 */

import com.study.springbootsecurity.enums.BusinessEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 统一响应类
 * @author ss_419
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    /**
     * 状态码
     */
    private Integer code = 200;
    /**
     * 是否成功
     */
    private boolean success = true;
    /**
     * 信息
     */
    private String msg;
    /**
     * 分页数据 或 列表数据的 总长度
     */
    private Long total;
    /**
     * 数据
     */
    private T data;

    public Result(BusinessEnum businessEnum) {
        this.code = businessEnum.getCode();
        this.msg = businessEnum.getDesc();
    }

    public Result(Integer code, boolean success, String msg, Long total) {
        this.code = code;
        this.success = success;
        this.msg = msg;
        this.total = total;
    }


    public Result(Integer code, boolean success, String msg) {
        this.code = code;
        this.success = success;
        this.msg = msg;
    }

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setMsg("ok");
        result.setData(data);
        return result;
    }

    public static <T> Result<T> success(Long total,T data) {
        Result<T> result = new Result<>();
        result.setMsg("ok");
        result.setData(data);
        result.setTotal(total);
        return result;
    }

    public static <T> Result<T> success() {
        Result<T> result = new Result<>();
        result.setMsg("ok");
        return result;
    }

    public static <T> Result<T> fail(BusinessEnum businessEnum) {
        Result<T> result = new Result<>();
        result.setCode(businessEnum.getCode());
        result.setSuccess(false);
        result.setMsg(businessEnum.getDesc());
        return result;
    }

    public static <T> Result<T> fail(Integer code, String msg) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setSuccess(false);
        result.setMsg(msg);
        return result;
    }

    public static <T> Result<T> fail( String msg) {
        Result<T> result = new Result<>();
        result.setSuccess(false);
        result.setMsg(msg);
        return result;
    }

    public static Result<String> handle(boolean flag) {
        if (flag) {
            return success(null);
        }
        return fail(BusinessEnum.OPERATION_FAIL);
    }
}
